import $ = require("jquery")
import Dialog, { DialogStatic, OptionGenerate_NormalShowTypeDialog } from "../../logic/page/dialog";
import KeyValuePairsDb, { OperableStoreShow } from "../../logic/database/KeyValuePairsDb";
import WebCache from "../../logic/database/webcache";
import "css!./_dialog_select.s.css"
import GetConfigJSON from "../../logic/network/config";
import loading from "../../logic/page/loading";

/** 已选择操作存储区 */
const KEY_SelectedOperableStore = "KEY:SelectedOperableStore";

const cache = new WebCache();
const db = new KeyValuePairsDb();

/**
 * 操作数据存储区加载方法
 * @param callback 获取到存储区, 回调执行方法
 */
export function OperableDataStoreOnLoad(callback: (store: OperableStoreShow) => void): void {
    let json = cache.Get(KEY_SelectedOperableStore);
    if (json === null) {
        // 打开选择
        OpenSelectDialogPage(callback);
        return;
    }
    let store = JSON.parse(json) as OperableStoreShow;
    callback(store);
}

/**
 * 直接打开存储区选择窗页面
 * @param callback 获取到存储区, 回调执行方法
 */
export async function OpenSelectDialogPage(callback: (store: OperableStoreShow) => void): Promise<void> {
    loading.open();
    var list = await db.GetOperableStores();
    loading.close();
    if (!list) {
        $.messager.alert({
            title: "加载操作区域",
            icon: "error",
            msg: "加载失败, 查询数据为空!",
        });
        return;
    }
    let config = await GetConfigJSON();
    loading.open();
    let dialog_conf: OptionGenerate_NormalShowTypeDialog = {
        title: "选择操作存储区",
        url: `${config.BaseUrl}/functions/operable_data_store/_dialog_select.html`,
        style: {
            width: "600px",
            height: "500px",
        },
        loadFunc: function(dialog: Dialog) {
            let form = dialog.GetDialog().find("form");
            form.form('load', {
                storesDataSource: list,
                callback: function(index: number) {
                    let store = list[index];
                    cache.Set(KEY_SelectedOperableStore, JSON.stringify(store));
                    dialog.Close();
                    callback(store);
                },
            });
        },
        closeFunc: function(dialog: Dialog) {
            loading.close();
        },
    };
    DialogStatic.ToGenerate_NormalShowTypeDialog(dialog_conf).Create().Open();
}
